package it.tcm.TeacherClassMate.writer;

import it.tcm.TeacherClassMate.beans.EquationBean;
import it.tcm.TeacherClassMate.beans.OrderMainBean;
import it.tcm.TeacherClassMate.beans.OrderRowBean;
import it.tcm.TeacherClassMate.facade.EquationManageBase;
import it.tcm.TeacherClassMate.persistent.DBConnection;
import it.tcm.TeacherClassMate.util.OrderRowBeanComparator;
import it.tcm.TeacherClassMate.util.Util;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import javax.naming.InitialContext;
import org.apache.log4j.Logger;
import org.docx4j.jaxb.Context;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;
import org.docx4j.wml.Jc;
import org.docx4j.wml.JcEnumeration;
import org.docx4j.wml.ObjectFactory;


public class ResultWriter {
	
	private Logger logger = Logger.getLogger(this.getClass().getName());
	
	@SuppressWarnings("unchecked")
	public boolean createResult(OrderMainBean omb)  {
	
		 try {
			 javax.naming.Context ctx = new InitialContext();
			 String docxFileDir = (String)ctx.lookup("java:comp/env/docxPath");
			 DBConnection db = new DBConnection();
			 Connection conn = db.getDBConnection();
			 Statement stmt = conn.createStatement();
			 ResultSet rs = null;
			 String xpath = "//w:p";
		     List<org.docx4j.wml.P> arrayOfParag = new ArrayList<org.docx4j.wml.P>();
					 
			 ObjectFactory factory = Context.getWmlObjectFactory();
			 
			 // devo fare il merge dei docx delle equazioni			 
			 ArrayList<OrderRowBean> array  = new ArrayList<OrderRowBean>(omb.getOrderRows()); 
			 Collections.sort(array,new OrderRowBeanComparator());
			 
			 for (OrderRowBean ob : array)  {
				 
				 String table = null;
				 String id = ob.getIdForm().toString();
				 String result_string = null;
				 if (ob.getIdTypology().equals(Util.EQUATIONS_TYPOLOGY)) {
					 table = Util.EQUATION; 
					 Integer idForm = ob.getIdForm();
					 EquationManageBase eqm = new EquationManageBase();
					 EquationBean eq = eqm.getEquationById(idForm);
					 result_string = eq.getResultString();
				 } else {
					 //....
				 }
				 
				 // recupero il documento da blob
				 Blob result = null;
				 stmt = conn.createStatement();
				 rs = stmt.executeQuery("select result from " + table + " where id = " + id);
				 InputStream resultdoc = null;
				 if (rs.next()) {
				    result = rs.getBlob(1);
				    if (result != null) {
					  resultdoc = result.getBinaryStream();
				    } else {					  
					  //take it from file
				       File file = null;
					   if (table.equals("EQUATION")) {
							String equationDocxFileDir = docxFileDir + "//E//";
							file = new File(equationDocxFileDir + "E" + id + "_result.docx");
							if (file != null)  resultdoc = new FileInputStream(file);	
					   }  
				    }		
				 }
	
				 
				 // Create the paragraph 4 intestazione esercizio
				 org.docx4j.wml.P p0= factory.createP();
				 // Create the text element
				 org.docx4j.wml.Text t0= factory.createText();
				 t0.setValue("Risultato esercizio numero: " + ob.getPosition());
			     org.docx4j.wml.Color c0 =factory.createColor();
	             c0.setVal("FF0000");
	             org.docx4j.wml.R r0 = factory.createR();
	             org.docx4j.wml.RPr rpr0 = factory.createRPr();
	             rpr0.setColor(c0);
                 r0.setRPr(rpr0);
                 r0.getContent().add(t0);
                 Jc jc0 = Context.getWmlObjectFactory().createJc();
                 jc0.setVal(JcEnumeration.LEFT);
                 org.docx4j.wml.PPr ppr0 = factory.createPPr();
                 ppr0.setJc(jc0);
                 p0.setPPr(ppr0);
                 p0.getContent().add(r0);      			
				 arrayOfParag.add(p0);
				 
				 if (resultdoc != null) {					 
					 // aggiungo i paragrafi del risultato
					 WordprocessingMLPackage formula = WordprocessingMLPackage.load(resultdoc);
					 MainDocumentPart documentPartFormula = formula.getMainDocumentPart();
					 List<Object> listpformula = documentPartFormula.getJAXBNodesViaXPath(xpath, false);				
					 for (Object obj : listpformula) {
							org.docx4j.wml.P para0 = (org.docx4j.wml.P)obj;
							List<Object> listr = para0.getContent();
							if (listr != null && listr.size() != 0) {
								arrayOfParag.add(para0);
							}
					 }					 
				 } else {
					 // result_string	
					 org.docx4j.wml.P p1= factory.createP();
					 // Create the text element
					 org.docx4j.wml.Text t1= factory.createText();
					 t1.setValue(result_string);
				     org.docx4j.wml.Color c1 =factory.createColor();
		             c1.setVal("000000");
		             org.docx4j.wml.R r1 = factory.createR();
		             org.docx4j.wml.RPr rpr1 = factory.createRPr();
		             rpr1.setColor(c1);
	                 r0.setRPr(rpr1);
	                 r0.getContent().add(t1);
	                 Jc jc1 = Context.getWmlObjectFactory().createJc();
	                 jc1.setVal(JcEnumeration.CENTER);
	                 org.docx4j.wml.PPr ppr1 = factory.createPPr();
	                 ppr1.setJc(jc1);
	                 p1.setPPr(ppr1);
	                 p1.getContent().add(r1);      			
					 arrayOfParag.add(p1);		
				 }
			 
				 // Create the paragraph 4 punteggio
				 org.docx4j.wml.P para= factory.createP();
				 // Create the text element
				 org.docx4j.wml.Text t= factory.createText();
				 t.setValue("Punteggio assegnato all'esercizio : " + ob.getPoints());
			     org.docx4j.wml.Color color =factory.createColor();
	             color.setVal("FF0000");
	             org.docx4j.wml.R run = factory.createR();
	             org.docx4j.wml.RPr rpr = factory.createRPr();
	             rpr.setColor(color);
                 run.setRPr(rpr);
                 run.getContent().add(t);
                 Jc jc = Context.getWmlObjectFactory().createJc();
                 jc.setVal(JcEnumeration.RIGHT);
                 org.docx4j.wml.PPr ppr = factory.createPPr();
                 ppr.setJc(jc);
                 para.setPPr(ppr);
                 para.getContent().add(run);      			
				 arrayOfParag.add(para);
				 
				 resultdoc.close();
			 }
			 
			 // Create the package
		     WordprocessingMLPackage wordMLPackage = new WordprocessingMLPackage();
			 // Create the main document part (word/document.xml)
			 MainDocumentPart wordDocumentPart = new MainDocumentPart();
			 org.docx4j.wml.Body body = factory.createBody();
			 body.getContent().addAll(arrayOfParag);
			 org.docx4j.wml.Document wmlDocumentEl = factory .createDocument();
		     wmlDocumentEl.setBody(body);
			 // Put the content in the part
			 wordDocumentPart.setJaxbElement(wmlDocumentEl);
			 wordMLPackage.addTargetPart(wordDocumentPart);
			 long lDateTime = new Date().getTime();
			 File filedocx = new File(docxFileDir + "//verif_"+ String.valueOf(lDateTime) + "_result.docx");
			 wordMLPackage.save(filedocx);
			 FileInputStream fisdocx = new FileInputStream(filedocx);
			 
			
			 String sql = "update ORDERMAIN set result = ? WHERE id = ?";
			 PreparedStatement stmt0 = conn.prepareStatement(sql);    
			 stmt0.setInt(2, omb.getId());    
			 logger.info("fisdo avaliable" + fisdocx.available());  
			 logger.info("filedocx.length()" + filedocx.length());   		    	   
			 stmt0.setBinaryStream(1, fisdocx, (int) filedocx.length()); // ri-metto il docx				 
			 stmt0.execute();
			 fisdocx.close();
			 conn.close();
			 filedocx.delete();
			 
		 } catch(Exception e) {
			 logger.error("Exception e " + e.getMessage());
			 e.printStackTrace();
		 }

	  
	 return true;
	  
   }

}
